package com.gmall.rabbitmq.producer.controller;

import com.gmall.rabbitmq.config.RabbitMQConfig_Reliable;
import com.gmall.rabbitmq.producer.utils.IdWorker;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/reliable")
public class ReliableController {

    @Autowired
    RabbitTemplate rabbitTemplate;


    @GetMapping("/produce/nonEx")
    public String produceNonEx(){
        /**
         * String exchange 交换机
         * String routingKey 路由键
         * Object object 消息内容
         */
        rabbitTemplate.convertAndSend(
                "notExist",
                "anyThing"
                ,"hello,world");
        return "OK";
    }

    @GetMapping("/produce/ex/NoRoutingKey")
    public String produceNoRoutingKey(){
        /**
         * String exchange 交换机
         * String routingKey 路由键
         * Object object 消息内容
         */
        rabbitTemplate.convertAndSend(
                RabbitMQConfig_Reliable.Exchange_Direct_Reliable,
                "weixin"
                ,"hello,world");
        return "OK";
    }

    @Autowired
    IdWorker idWorker;
    @GetMapping("/produce")
    public String produceMessage(){

        /**
         * String exchange, 交换机
         * String routingKey, 路由key
         * Object message, 消息
         * MessagePostProcessor messagePostProcessor, 设置消息唯一ID和持久化
         * @Nullable CorrelationData correlationData 用户生产端Confirm
         */

        Long messageId = idWorker.nextId();

        rabbitTemplate.convertAndSend(RabbitMQConfig_Reliable.Exchange_Direct_Reliable,
                RabbitMQConfig_Reliable.RoutingKey_Reliable,
                "HelloWorld!",
                (message)->{
                    //设置消息的唯一id
                    message.getMessageProperties().setMessageId(String.valueOf(messageId));
                    //消息持久化
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                },
                new CorrelationData(String.valueOf(messageId)));
        return "OK";
    }

    
}
